package org.huang.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * @author hdu_huang
 * @since 2024/7/3 10:25
 */
@Slf4j
public final class JsonUtil {

    private JsonUtil() {
    }

    private static final JsonMapper jsonMapper = new JsonMapper();

    static {
        //处理 java8 time api
        jsonMapper.registerModule(new JavaTimeModule());

        //key是单引号解析，标准key为双引号
        jsonMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

        //序列化
        //取消时间的转化格式, 默认是时间戳
        jsonMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //如果是空对象的时候,不抛异常
        jsonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        //发序列化配置
        //反序列化的时候如果多了其他属性,不抛出异常
        jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


    }

    public static String toJson(Object object) {

        if (object == null) {
            return null;
        }

        String json = null;

        try {
            json = jsonMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
        return json;
    }

    public static <T> T fromJson(String json, Class<T> classType) {

        if (json == null) {
            return null;
        }

        T object = null;

        try {
            object = jsonMapper.readValue(json, classType);
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return object;
    }

    public static <T> List<T> getListFromJson(String json, Class<T> classType) {

        if (json == null) {
            return null;
        }

        List<T> lists = null;
        try {
            //默认ArrayList
            JavaType javaType = jsonMapper.getTypeFactory().constructCollectionType(List.class, classType);
            lists = jsonMapper.readValue(json, javaType);
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return lists;
    }

}
